package and.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.youmi.android.AdManager;
import net.youmi.android.appoffers.CheckStatusNotifier;
import net.youmi.android.appoffers.YoumiOffersManager;
import net.youmi.android.appoffers.YoumiPointsManager;
import and.common.MyCommon;
import and.process.QueryProcess;
import and.tools.FileHelper;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.gfan.sdk.statitistics.GFAgent;

public class MainActivity extends BaseActivity implements CheckStatusNotifier {

	protected ExpandableListView elv;

	@Override
	protected void onResume() {
		GFAgent.onResume(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		GFAgent.onPause(this);
		super.onPause();
	}

	protected MyExpandableListAdapter adapter;
	private int tabCount = 4;

	protected void bindList() {
		List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
		Map<String, String> group = new HashMap<String, String>();
		for (int i = 0; i < MyCommon.CPFENLEI.length; i++) {
			group = new HashMap<String, String>();
			group.put(MyCommon.CPLEIXING, MyCommon.CPFENLEI[i]);
			groups.add(group);
		}
		List<Map<String, String>> child1 = new ArrayList<Map<String, String>>();
		Map<String, String> child;
		for (int i = 0; i < MyCommon.FCWANFA.length; i++) {
			child = new HashMap<String, String>();
			child.put(MyCommon.CPWANFA, MyCommon.FCWANFA[i]);
			child1.add(child);
		}

		List<Map<String, String>> child2 = new ArrayList<Map<String, String>>();
		for (int i = 0; i < MyCommon.TCWANFA.length; i++) {
			child = new HashMap<String, String>();
			child.put(MyCommon.CPWANFA, MyCommon.TCWANFA[i]);
			child2.add(child);
		}

		List<Map<String, String>> child3 = new ArrayList<Map<String, String>>();
		for (int i = 0; i < MyCommon.DFWANFA.length; i++) {
			child = new HashMap<String, String>();
			child.put(MyCommon.CPWANFA, MyCommon.DFWANFA[i]);
			child3.add(child);
		}

		List<List<Map<String, String>>> childs = new ArrayList<List<Map<String, String>>>();
		childs.add(child1);
		childs.add(child2);
		childs.add(child3);
		adapter = new MyExpandableListAdapter(this, groups, R.layout.mainlist,
				new String[] { MyCommon.CPLEIXING }, new int[] { R.id.group },
				childs, R.layout.mainsecondlist,
				new String[] { MyCommon.CPWANFA }, new int[] { R.id.child });
		setContentView(R.layout.main);
		elv = (ExpandableListView) findViewById(android.R.id.list);
		elv.setAdapter(adapter);

		// if (MyCommon.isExpand) {
		// for (int i = 0; i < groups.size(); i++) {
		// elv.expandGroup(i);
		// }
		// }
		elv.setOnChildClickListener(new OnChildClickListener() {
			/*
			 * 选择要查询的彩票种类
			 * 
			 * @seeandroid.app.ExpandableListActivity#onChildClick(android.widget
			 * . ExpandableListView, android.view.View, int, int, long)
			 */
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				HashMap<String, String> map = (HashMap<String, String>) adapter
						.getChild(groupPosition, childPosition);
				String selectName = map.get(MyCommon.CPWANFA);
				boolean flag = false;
				try {
					for (int i = 0; i < MyCommon.TCWANFA.length; i++) {
						if (selectName.equals(MyCommon.TCWANFA[i])) {
							flag = true;
						}
					}
					for (int i = 0; i < MyCommon.FCWANFA.length; i++) {
						if (selectName.equals(MyCommon.FCWANFA[i])) {
							flag = true;
						}
					}
					if (flag) {
						query(selectName);
					} else {
						if (selectName.equals(MyCommon.DFGUANGDONG)) {
							new AlertDialog.Builder(getNowActivity())
									.setTitle("选择玩法")
									.setItems(MyCommon.GDWANFA,
											new OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													query(MyCommon.GDWANFA[which]);
												}
											}).show();
						}
					}

				} catch (Exception e) {
					System.out.println("切换activity出错");
					e.printStackTrace();
				}
				return true;
			}
		});
	}

	private void query(String selectName) {
		TabActivity ta = (TabActivity) MainActivity.this.getParent();
		TabHost tabHost = ta.getTabHost();
		QueryProcess query = new QueryProcess();
		query.initQuery(selectName);
		if (tabHost.getTabWidget().getChildCount() == tabCount) {
			tabHost.addTab(tabHost
					.newTabSpec("result")
					.setIndicator("结果",
							getResources().getDrawable(R.drawable.result))
					.setContent(
							new Intent(MainActivity.this, QueryActivity.class)));
		} else {
			tabHost.getTabWidget().removeViewAt(tabCount);
			tabHost.addTab(tabHost
					.newTabSpec("result")
					.setIndicator("结果",
							getResources().getDrawable(R.drawable.result))
					.setContent(
							new Intent(MainActivity.this, QueryActivity.class)));
		}
		tabHost.setCurrentTabByTag("result");
	}

	/*
	 * 绑定列表的数据
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setNowActivity(this);
		bindList();
		YoumiOffersManager.init(this, "a6d846f06b30e501", "bfb520754e94fb8c");
		findViewById(R.id.btnRemoveAd).setOnClickListener(
				new View.OnClickListener() {

					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (YoumiPointsManager.queryPoints(MainActivity.this) == 0) {
							Toast.makeText(
									MainActivity.this,
									"去除广告需要20积分，您需要下载推荐应用获取积分", 2000).show();
							YoumiOffersManager.showOffers(MainActivity.this,
									YoumiOffersManager.TYPE_REWARD_OFFERS);
						} else if (YoumiPointsManager
								.queryPoints(MainActivity.this) < 20) {
							Toast.makeText(
									MainActivity.this,
									"去除广告需要20积分，您只有"
											+ YoumiPointsManager
													.queryPoints(MainActivity.this)
											+ "分", 2000).show();
							YoumiOffersManager.showOffers(MainActivity.this,
									YoumiOffersManager.TYPE_REWARD_OFFERS);
						} else {
							SharedPreferences sp =MainActivity.this.getSharedPreferences("ad",MODE_PRIVATE);
							Editor ed = sp.edit();
							ed.putString("has", "no");
							ed.commit();
							YoumiPointsManager.spendPoints(MainActivity.this,
									20);
							findViewById(R.id.flAd).setVisibility(View.GONE);
							findViewById(R.id.btnRemoveAd).setVisibility(View.GONE);
						}

					}
				});
		YoumiOffersManager.checkStatus(MainActivity.this,
				MainActivity.this);
		SharedPreferences sp =this.getSharedPreferences("ad",MODE_PRIVATE);
		if (!"test".equals(FileHelper
				.getText("http://android.snbw.cn/test.txt")) && !"no".equals(sp.getString("has", ""))) {
			AdManager.init(MainActivity.this, "a6d846f06b30e501",
					"bfb520754e94fb8c", 31, false);
		} else {
			findViewById(R.id.flAd).setVisibility(View.GONE);
			findViewById(R.id.btnRemoveAd).setVisibility(View.GONE);
		}
	}

	public void onCheckStatusConnectionFailed(Context arg0) {
		// TODO Auto-generated method stub

	}

	public void onCheckStatusResponse(Context context, boolean isAppInvalid,
			boolean isInTestMode, boolean isDeviceInvalid) {
		System.out
				.println(new StringBuilder(256)
						.append("检查App及当前设备状态成功\n=>>App状态:")
						.append(isAppInvalid ? "[异常]" : "[正常]")
						.append("\n=>>是否为测试模式:")
						.append(isInTestMode ? "[测试模式]" : "[正常模式]")
						.append("\n=>>当前设备状态:")
						.append(isDeviceInvalid ? "[异常]" : "[正常]")
						.append("\n只有三个状态都为正常时，才可以获得收入。但无论状态是否异常，用户完成积分墙模式下的Offer后都可以获得积分。")
						.append("\n\n如果您使用的是积分墙模式并且希望所有设备都可以获得积分，可以不调用该检查接口或不处理检查结果。")
						.append("\n如果您使用的是积分墙模式并且希望在保证有收入的情况下用户才能够获得相应的积分，那么您应该在使用积分墙前，先调用此接口进行状态判断，如果状态都为正常时才启用积分墙。")
						.append("\n\n如果App状态不正常或为\"测试模式\"，请确认是否已经上传应用到有米主站并通过审核，上传应用前，请先忽略该状态检查接口，正常调用积分墙，以配合审核人员进行审核。")
						.append("\n\n在调用状态检查接口前，请务必先进行初始化。该接口成功调用一次即可，不需要多次调用。")
						.toString());
	}

	public class MyExpandableListAdapter extends SimpleExpandableListAdapter {
		public MyExpandableListAdapter(Context context,
				List<? extends Map<String, ?>> groupData, int groupLayout,
				String[] groupFrom, int[] groupTo,
				List<? extends List<? extends Map<String, ?>>> childData,
				int childLayout, String[] childFrom, int[] childTo) {
			super(context, groupData, groupLayout, groupFrom, groupTo,
					childData, childLayout, childFrom, childTo);
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, 64);
			LinearLayout ll = new LinearLayout(MainActivity.this);
			ll.setLayoutParams(lp);
			ll.setOrientation(LinearLayout.HORIZONTAL);

			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			params.gravity = Gravity.CENTER;
			params.setMargins(36, 0, 0, 0);
			TextView tvName = new TextView(MainActivity.this);
			tvName.setLayoutParams(params);
			// Center the text vertically
			tvName.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			// Set the text starting position
			tvName.setPadding(16, 0, 0, 0);
			tvName.setTextSize(20);
			HashMap<String, String> group = (HashMap<String, String>) getGroup(groupPosition);
			tvName.setText(group.get(MyCommon.CPLEIXING).toString());
			ll.addView(tvName);
			return ll;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, 60);
			LinearLayout ll = new LinearLayout(MainActivity.this);
			ll.setLayoutParams(lp);
			ll.setOrientation(LinearLayout.HORIZONTAL);

			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			params.gravity = Gravity.CENTER;
			params.setMargins(56, 0, 0, 0);
			TextView tvName = new TextView(MainActivity.this);
			tvName.setLayoutParams(params);
			tvName.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			tvName.setTextSize(18);
			HashMap<String, String> child = (HashMap<String, String>) getChild(
					groupPosition, childPosition);
			tvName.setText(child.get(MyCommon.CPWANFA).toString());
			ll.addView(tvName);
			return ll;
		}

		@Override
		public void onGroupExpanded(int groupPosition) {
			super.onGroupExpanded(groupPosition);
		}
	}
}
